//
//  LXRecommendCircleView.swift
//  zhibo
//
//  Created by Echo on 16/9/26.
//  Copyright © 2016年 Echo. All rights reserved.
//

import UIKit

private let kCircleCellId = "kCircleCellId"

class LXRecommendCircleView: UIView {

    var circleTimer : NSTimer?
    var circleModels : [LXCircleModel]? {
        didSet {
            // 1
            collectionView.reloadData()
            //
            pageControl.numberOfPages = circleModels?.count ?? 0
            
            // 默认滚到某一位置
            let indexPath = NSIndexPath(forItem: (circleModels?.count ?? 0) * 10 , inSection: 0)
            collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: .Left, animated: false)
            
            // 添加自动播放
            removeTimer()
            addTimer()
        }
    }
    
    @IBOutlet weak var pageControl: UIPageControl!
    @IBOutlet weak var collectionView: UICollectionView!
    
    override func awakeFromNib() {
        super.awakeFromNib()
        
        autoresizingMask = .None
        
        collectionView.registerNib(UINib(nibName: "LXRecommendCircleCell",bundle: nil), forCellWithReuseIdentifier: kCircleCellId)
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
        layout.itemSize = collectionView.bounds.size
        
    }
}

extension LXRecommendCircleView {
    class func recommendCircleView() -> LXRecommendCircleView{
        return NSBundle.mainBundle().loadNibNamed("LXRecommendCircleView", owner: nil, options: nil).first as! LXRecommendCircleView
        
    }
}

extension LXRecommendCircleView : UICollectionViewDataSource {
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return (circleModels?.count ?? 0) * 1000
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(kCircleCellId, forIndexPath: indexPath) as! LXRecommendCircleCell
        
        cell.circleModel = circleModels![indexPath.item % circleModels!.count]
        
        return cell
    }
}

extension LXRecommendCircleView : UICollectionViewDelegate {
    func scrollViewDidScroll(scrollView: UIScrollView) {
        let offsetX = scrollView.contentOffset.x + scrollView.bounds.width * 0.5
        
        // 当前页面；模数是为了从最后一页重新滚到第一页
        pageControl.currentPage = Int(offsetX / scrollView.bounds.width) % (circleModels?.count ?? 1)
    }
    
    // 即将开始手动滚动，取消定时器
    func scrollViewWillBeginDragging(scrollView: UIScrollView) {
        removeTimer()
    }
    
    // 即将结束手动滚动，增加定时器
    func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        addTimer()
    }
}

extension LXRecommendCircleView {
    private func addTimer(){
        
        circleTimer = NSTimer(timeInterval: 3.0, target: self, selector: #selector(self.scrollToNext), userInfo: nil, repeats: true)
        NSRunLoop.mainRunLoop().addTimer(circleTimer!, forMode: NSRunLoopCommonModes)
        
    }
    
    private func removeTimer(){
        circleTimer?.invalidate()
        circleTimer = nil
        
    }
    
    @objc private func scrollToNext(){
        
        let currentOffsetX = collectionView.contentOffset.x
        let offsetX = currentOffsetX + collectionView.bounds.width
        
        // 滚动到该位置
        collectionView.setContentOffset(CGPoint(x: offsetX,y: 0), animated: true)
        
    }
}
